package com.thread;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

public class PipelineThread {
	static class PipelineThreadWrite implements Runnable{
		PipedOutputStream out;
		
		public PipelineThreadWrite(PipedOutputStream out) {
			super();
			this.out = out;
		}

		public void writeMethod(PipedOutputStream out) throws IOException {
			System.out.println("write :");
			for (int i = 0; i < 300; i++) {
				String outData = "" + (i+1);
				out.write(outData.getBytes());
				System.out.print(outData + " ");
			}
			System.out.println();
			out.close();
		}

		@Override
		public void run() {
			try {
				writeMethod(out);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	static class PipelineThreadRead implements Runnable{
		PipedInputStream in;
		
		public PipelineThreadRead(PipedInputStream in) {
			super();
			this.in = in;
		}

		public void readMethod(PipedInputStream in) throws IOException {
			System.out.println("read :");
			byte[] br = new byte[20];
			int readLength = in.read(br);
			
			while(readLength != -1) {
				String newData = new String(br, 0, readLength);
				System.out.println(newData);
				readLength = in.read(br);
			}
			System.out.println();
			in.close();
		}

		@Override
		public void run() {
			try {
				readMethod(in);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) throws IOException, InterruptedException {
		PipedInputStream ip = new PipedInputStream();
		PipedOutputStream op = new PipedOutputStream();
		ip.connect(op);
		
		PipelineThreadWrite pw = new PipelineThreadWrite(op);
		PipelineThreadRead pr = new PipelineThreadRead(ip);
		
		Thread t1 = new Thread(pw);
		Thread t2 = new Thread(pr);
		
		t1.start();
		Thread.sleep(2000L);
		t2.start();
		
	}
}
